package cn.my.learning.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * Created by Leo on 2017/4/6.
 * 文件操作类
 */
public class FileUtil {
    /**
     * 复制文件
     * @param fromFilePath
     * @param toFile
     * <br/>
     * 2017年4月6日
     * @throws IOException
     */
    public boolean copyFile(String fromFilePath, String toFile) throws IOException
    {
        try {
            File fromFile = new File(fromFilePath);

            int byte_sum = 0;
            int byte_read;

            //文件存在时
            if (fromFile.exists()) {
                //读入原文件
                InputStream inStream = new FileInputStream(fromFile);
                FileOutputStream fs = new FileOutputStream(new File(toFile + "\\userInfo.png"));
                System.out.println(fs);
                byte[] buffer = new byte[4096];
                while ( (byte_read = inStream.read(buffer)) != -1) {
                    //字节数 文件大小
                    byte_sum += byte_read;
                    fs.write(buffer, 0, byte_read);
                }
                inStream.close();
                fs.close();
            }
        }  catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //inputFormat表示原格式，outputFormat表示转化后的格式
    public String Conversion(String inputFormat, String src){

        try {
            File input = new File(src + "." + inputFormat);

            BufferedImage bim = ImageIO.read(input);

            File output = new File(src + "." + "png");

            //删除其他格式的源文件
            input.delete();

            ImageIO.write(bim, "png", output);

            return output.toString();
        } catch (IOException e) {
            System.out.println("转换失败");
            e.printStackTrace();
        }
        return "Null";
    }
}
